package com.r2dbc.repository.impl;

import com.google.gson.Gson;
import com.r2dbc.domain.User;
import com.r2dbc.domain.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/*
 *@Description<p></p>
 *@Author gz
 *@CreateTime 2025/8/12 20:46
 *@CopyRight @2021-2025 卓望信息技术（北京）公司
 */
@Service
public class MyUserRepository {
    @Autowired
    DatabaseClient databaseClient;

    public Flux<User> dbClientQuery(Long id) {
        return databaseClient.sql("SELECT  u.*  from USER u LEFT JOIN ROLE r  ON  u.role_id = r.id where u.id = :id")
                .bind("id", id)
                .fetch() // 抓取数据
                .all()// 期望只返回一行数据
                .map((stringObjectMap -> {
                    System.out.println("map:" + stringObjectMap);
                    Gson gson = new Gson();
                    String json = gson.toJson(stringObjectMap);
                    User user = gson.fromJson(json, User.class);
                    return user;
                }));
    }

    public Flux<UserDetail> dbClientQueryAll() {
        return databaseClient.sql("SELECT  u.*,r.name as roleName  from USER u LEFT JOIN ROLE r  ON  u.role_id = r.id ")
                .fetch() // 抓取数据
                .all()// 期望只返回一行数据
                .map((stringObjectMap -> {
                    System.out.println("map:" + stringObjectMap);
                    UserDetail userDetail = new UserDetail();
                    userDetail.setId(Long.valueOf(stringObjectMap.get("id").toString()));
                    userDetail.setName((String) stringObjectMap.get("name"));
                    userDetail.setPassword(stringObjectMap.get("password").toString());
                    userDetail.setAccount(stringObjectMap.get("account").toString());
                    userDetail.setRole_id(Long.valueOf(stringObjectMap.get("role_id").toString()));
                    userDetail.setRoleName((String) stringObjectMap.get("roleName"));

                    return userDetail;
                }));
    }

}
